import Settings from '@/utils/settings'
import { register, checkCode, saveTokenToServer, login } from '@/apis/user'
import { saveToken } from '@/apis/abnormalFeedback/index'
import { getUserLocation } from '@/apis/common'

const state = {
	// 获取验证码所用的手机号
	mobile: '',
	
	// 是否登录
	isLogin: false,
	
	// 用户信息
	userInfo: null,
	
	// 当前登陆用户
	username: '',
	
	// 头像
	avatarUrl: '',
	
	// 默认头像
	defaultAvatarUrl: require('@/static/images/avatar_001.jpg'),
	
	// 系统版本
	version: '1.5.7',
	
	// token
	token: '',
	
	// 经度
	longitude: '117.305029',
	
	// 纬度
	latitude: '31.705368',
	
	// 用户菜单权限集合
	menuPermissions: [],
	
	// 无需登录、权限的开放页面
	noAuthUrls: [
		"pages/guide/guide",
		"pages/login/login",
		"pages/captch/captch"
	]
}

const mutations = {
	// 设置当前用户位置
	setUserLocation(state, data) {
		state.longitude = data.longitude
		state.latitude = data.latitude
	},
	
	// 设置当前验证的手机号
	setMobile(state, phone) {
		state.mobile = phone
	},
	
	// 设置登录状态
	setLoginState(state, data) {
		state.isLogin = data
	},
	
	// 设置 token
	setToken(state, data) {
		state.token = data
	},
	
	// 设置用户信息
	setUserInfo(state, data) {
		state.userInfo = data
	},
	
	// 设置登录用户昵称
	setUserName(state, name) {
		state.username = name
	},
	
	// 设置登录用户头像
	setAvatar(state, url) {
		state.avatarUrl = url
	},
	
	// 设置当前用户菜单权限
	setMenuPermissions(state, menus) {
		state.menuPermissions = menus
	},
	
	// 退出登录
	logout(state) {
		state.mobile = ''
		state.isLogin = false
		state.userInfo = null
		state.username = ''
		state.avatarUrl = ''
		state.token = ''
		state.menuPermissions = []
	}
}

const actions = {
	// 退出登录
	logout(ctx) {
		return new Promise((resolve, reject) => {
			ctx.commit('logout')
			resolve()
		})
	},
	
	// 国四终端模块需要将 token 记录一下
	handleSaveToken(ctx, { token, userName }) {
		saveToken({ token, userName })
	},
	
	// 验证码输入后，校验验证码（如果校验成功拿到 token 完成登录，还需要请求一次接口，将 token 存入服务器）
	async login(ctx, data) {
		let systemInfo = await uni.getSystemInfo()
		// let mapInfo = await getUserLocation({ device_id: systemInfo.deviceId, key: Settings.TX_KEY })
		let PlatForm = systemInfo.platform === 'ios' ? 5 : 3  // 3 安卓，5 ios
		let Location = ctx.state.longitude + ',' + ctx.state.latitude
		let params = {
			RegistCode: data.code,
			MobileNum: data.phone,
			PlatForm,
			DeviceName: systemInfo.browserName,
			DeviceId: systemInfo.deviceId,
			AppId: "HMP_003",
			Location, // 先写死，后面再想办法获取
			OSName: "13",
			VNo: "1.5.7",
			shadow$_klass_: "class com.heli.hmp_core.systemmgr.vo.LoginRegisterParams",
			shadow$_monitor_: 0,
		}
		
		return new Promise((resolve, reject) => {
			checkCode(params).then(res => {
				let query = {
					AppId: "HMP_003",
					DeviceId: systemInfo.deviceId,
					VNo: "1.5.7",
					shadow$_monitor_: 0,
					OSName: "13",
					Location,
					shadow$_klass_: 'class com.heli.hmp_core.systemmgr.vo.LoginParams',
					shadow$_monitor_: 0,
				}
				
				login(query).then(result => {
					ctx.commit('setLoginState', true) // 设置登录状态（登录成功）
					ctx.commit('setToken', result.Token) // 设置 token
					ctx.commit('setUserInfo', result.User) // 将登录成功后的用户信息保存下来，方便存取
					ctx.commit('setUserName', result.User.RealName) // 将登录成功的用户昵称存下来，方便展示
					ctx.commit('setAvatar', result.User.HeadImage) // 将登录成功的用户头像存下来，方便展示
					ctx.commit('setMenuPermissions', result.Menu) // 将登录成功的用户菜单权限拿到，方便后面菜单做逻辑
					ctx.dispatch('handleSaveToken', { token: result.Token, userName: result.User.UserName }) // 国四终端模块记录 token 信息
					
					// 将 token 存入服务器
					// saveTokenToServer({ AppleToken: result.Token, Location, token: result.Token })
					resolve(res)
				}).catch(err => {
					reject(err)
				})
			}).catch(err => {
				reject(err)
			})
		})
	},
	
	// 检查手机号是否存在，如果不存在，获取短信验证码，否则提示用户已存在
	async getSMSCode(ctx, phone) {
		let systemInfo = await uni.getSystemInfo()
		let PlatForm = systemInfo.platform === 'ios' ? 5 : 3 // 3 安卓，5 ios
		let params = {
			MobileNum: phone,
			PlatForm,
			DeviceName: systemInfo.browserName,
			DeviceId: systemInfo.deviceId,
			AppId: "HMP_003",
			Location: ctx.state.longitude + ',' + ctx.state.latitude, // 先写死，后面再想办法获取
			OSName: "13",
			VNo: "1.5.7",
			shadow$_klass_: "class com.heli.hmp_core.systemmgr.vo.GetRegisteCodeParams",
			shadow$_monitor_: 0,
		}
		
		return new Promise((resolve, reject) => {
			register(params).then(res => {
				resolve(res)
			}).catch(err => {
				reject(err)
			})
		})
	}
}

const getters = {}

export default {
	namespaced: true,
	state,
	mutations,
	actions,
	getters
}